
#include "serialporthelper.h"
#include <QModelIndex>
#include <QAbstractItemModel>
#include <QAbstractListModel>
#include <QDebug>


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QQuickItem>
#include <QCursor>


 DeviceList devicelist;
 HostList hostlist;
 //QList<SerialPort*> serialList;
 SerialList serialBox;
 NetWorkList netBox;
 PortList portList;
 StationModel station;
 CheckUpdate checkupdate;
 //com10=new SerialPort("COM10","9600","8","0","1");

SerialPortHelper::SerialPortHelper(QObject *parent) : QObject(parent)
{

    connect(&checkupdate,&CheckUpdate::needUpdate,this,&SerialPortHelper::SoftUpdateDo);
    checkupdate.Check(station.getSoftCurrVer());
    querySerialInfo();
    serialBox.setCallbackFunc(recvDeviceCallBack);
    netBox.setCallbackFunc(recvHostCallBack);
    station.setRestartTime(HJ212::getDataTime());
    //devicelist.append(*(new Device("name","red")));

    //确认设备使用的端口是否已启用，未启用则启用，如已启用确认是否是同一协议，如果是同一协议确认是否地址码相同
//    serialList.append(new SerialPort("COM10","9600","8","0","1"));
//    serialList[0]->serialWrite("00000");
    //static DeviceModle device_list;
//	device_list = new DeviceModle();
}

void SerialPortHelper::SoftUpdateDo(const QString &s)
{
    qDebug()<<"SoftUpdateDo:"<<s;
    station.setSoftOnlineVer(s);
    station.setNeedUpdate(true);
}


void SerialPortHelper::recvDeviceCallBack(int devIndex,QString devName,QString res)
{
    //qDebug()<<dev<<"--"<<res<<"--\r\n";
    processRecvDeviceBackMsg(devIndex,devName,res);
}

void SerialPortHelper::recvHostCallBack(int hostIndex,QString hostName,QString res)
{
    //qDebug()<<hostIndex<<"--"<<res<<"--\r\n";
   processRecvHostBackMsg(hostIndex,hostName,res);
}



int SerialPortHelper::GetPortNumByName(QString portname)
{
//    for (int i=0;i<serialList.count();i++) {
//        if(QString::compare(serialList[i]->PortNameStr(),portname)==0)
//    }
    return -1;
}


QStringList SerialPortHelper::querySerialInfo()
{

    QStringList ports=serialBox.SerialRefresh();
    portList.setText(ports);

    return ports;

}

void SerialPortHelper::goUpDate()
{
    qDebug()<<"-goupdate-\r\n";

#if defined(Q_OS_WIN32)

    QString path=QDir::currentPath();//获取程序当前工作目录
    path.replace("/","\\");//将地址中的"/"替换为"\"，因为在Windows下使用的是"\"
    if(!QProcess::startDetached(path+"\\update.exe"))//启动主程序，主程序在其上一级目录
    {
       qDebug()<<"警告信息,启动升级程序错误!\r\n";
       return;
    }

#elif defined(Q_OS_LINUX)

    //return;

#endif

    qApp->quit();
}



//QList<Device> SerialPortHelper::queryDeviceInfo()
//{
//	//QList<Device> device_list;
//    //qDebug()<<devicelist;//[0].name<<devicelist[0].colorCode;
//    return devicelist.text();// device_list;
//}

//void SerialPortHelper::addDevice(QString name_, QString portname_, QString protocol_, QString addr_)
//{
//    devicelist.addDevice( name_,  portname_,  protocol_,  addr_);
//}

//void SerialPortHelper::addHost(QString name_, QString portname_, QString protocol_, QString addr_)
//{
//    devicelist.addDevice( name_,  portname_,  protocol_,  addr_);
//}

void SerialPortHelper::clickDeviceItem(int index)
{
    //取出设备(端口，设备协议，工作任务)
    Device device=devicelist.getdata()[index];

    //打开设备端口，根据工作任务调用协议数据生成方法指令数据，从端口发送指令
    serialBox.writeDataToSerial(index,device.name,device.portName,4800,8,0,1,1000,Flowmeter::getReadCmd(device.protocol,device.comAddr));

//    //等待取回端口数据，根据工作任务调用协议数据分析方法返回所需要的数据


//    //更新界面数据显示字串
//    QString timeStr = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
//    QString datastr="瞬时流量：1000 m3 "+timeStr;
//    devicelist.changeDataString(index,datastr);
}
void SerialPortHelper::clickHostItem(int index)
{
    HostSendAuto(1013,index);//时间校准请求
    HostSendAuto(2081,index);//上传数采仪开机时间

//    //取出平台信息(端口，设备协议，工作任务)
//    Host host=hostlist.getdata()[index];

//    //打开设备端口，根据工作任务调用协议数据生成方法指令数据，从端口发送指令
//    HJ212_DATA object;
//    object.QN=HJ212::getQN();
//    object.ST=32;
//    object.CN=1013;
//    object.PW=station.getPW();
//    object.MN=station.getMN();
//    netBox.writeDataToHost(index,host,500,HJ212::ResponseData(object,"PolId=w010118",5));//时间校准请求

//    object.QN=HJ212::getQN();
//    object.CN=2081;
//    object.CP="DataTime="+HJ212::getDataTime()+";RestartTime="+station.getRestartTime();
//    netBox.writeDataToHost(index,host,500,HJ212::ResponseData(object,object.CP,5));//上传数采仪开机时间
}



void SerialPortHelper::HostSendAuto(int CN,int hostIndex)
{

    //准备数据包
    HJ212_DATA object;
    object.QN=HJ212::getQN();
    object.ST=32;
    object.CN=CN;
    object.PW=station.getPW();
    object.MN=station.getMN();

    if(2011==CN)//上传/污染物ST=32/噪声声级ST=23/工况ST=52/实时数据
    {
        //object.CP="DataTime="+HJ212::getDataTime()+";RestartTime="+station.getRestartTime();
    }
    else if(2051==CN)//上传/污染物ST=32/噪声声级ST=23/分钟数据
    {

    }
    else if(2061==CN)//上传/污染物ST=32/噪声声级ST=23/小时数据
    {

    }
    else if(2031==CN)//上传/污染物ST=32/噪声声级ST=23/日历史数据
    {

    }
    else if(2021==CN)//上传设备运行状态
    {
        object.CP="DataTime="+HJ212::getDataTime()+";SB1-RS=2;SB2-RS=0...";
    }
    else if(3019==CN)//上传设备唯一标识
    {
        object.CP="DataTime="+HJ212::getDataTime()+";PolId=w010108;w010108-SN=010000A8900016F00169DC1";
    }
    else if(2041==CN)//上传设备运运时间日历史数据
    {
        object.CP="DataTime="+HJ212::getDataTime()+";SB1-RT=1.1;SB2-RT=2.1...";
    }
    else if(2081==CN)//上传数采仪开机时间
    {
        object.CP="DataTime="+HJ212::getDataTime()+";RestartTime="+station.getRestartTime();
    }
    else if(1013==CN)//时间校准请求
    {
        object.CP="PolId=w010118";
    }
    else if(3020==CN)//上传现场机信息
    {
        //(日志)
        object.CP="DataTime="+HJ212::getDataTime()+";PolId=w010108;i11001-Info=//清洗管路//";
        //object.CP=object.CP.toLatin1();
//        //(状态)
//        object.CP="DataTime="+HJ212::getDataTime()+";PolId=w010108;i12001-Info=1;i12003-Info=0";
//        //(参数)
//        object.CP="DataTime="+HJ212::getDataTime()+";PolId=w010108;i13004-Info=168.0;i13005-Info=40";
    }
    else if(3019==CN)//上传现场机信息(状态)
    {
        object.CP="DataTime="+HJ212::getDataTime()+";PolId=w010108;i11001-Info=//清洗管路//";
    }

    if(hostIndex>=0)//发送到指定平台
    {
        //object.CP=object.CP.toLatin1();
        netBox.writeDataToHost(hostIndex,hostlist.getdata()[hostIndex],500,HJ212::ResponseData(object,object.CP,5));//s
    }
    else//发送到所有平台
    {
        for(int i=0;i<hostlist.getdata().size();i++)
        {
            netBox.writeDataToHost(i,hostlist.getdata()[i],500,HJ212::ResponseData(object,object.CP,5));//s
        }
    }


}


void SerialPortHelper::processRecvDeviceBackMsg(int index,QString dev,QString res)
{
    //取出设备(端口，设备协议，工作任务)
    Device device=devicelist.getdata()[index];

    //根据设备协议解析数据，并返回显示字符串

    //qDebug()<<index<<dev<<"--"<<res<<"--\r\n";
    QString datares=Flowmeter::getDataResultStr(device.protocol,device.comAddr,res);
    //更新界面数据显示字串
    QString timeStr = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString datastr=datares+" "+timeStr;
    devicelist.changeDataString(index,datastr);
}

void SerialPortHelper::processRecvHostBackMsg(int index,QString hostname,QString res)
{
    //取出设备(端口，设备协议，工作任务)
    Host host=hostlist.getdata()[index];

    //根据设备协议解析数据，并返回显示字符串

    //qDebug()<<index<<dev<<"--"<<res<<"--\r\n";
    HJ212_DATA object;
    int error=HJ212::getDataObject(res,object,station);
    if(0==error)
    {
        QString datares;//=res;//Flowmeter::getDataResultStr(device.protocol,device.comAddr,res);
        datares.sprintf("ST:%d,CN:%d,Flag:%d",object.ST,object.CN,object.Flag);
        if(object.CP.size()>0) datares+=",CP:"+object.CP;
        //更新界面数据显示字串
        QString timeStr = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString datastr=datares+" "+timeStr;
        hostlist.changeDataString(index,datastr);

        //处理数据

        if(1000==object.CN)
        {
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//"QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));
            HJ212::recvCN1000(object.CP,station);
            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(1011==object.CN)
        {
            QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToHost(index,host,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));
            //如有污染物编码则取出污染物编码
            if(object.CP.size()>5)
            {
                QString polId=HJ212::recvCN1011(object.CP);
                //找出对应设备，根据协议取出设备的时间
                cpStr="polId="+polId+";SystemTime="+station.getSystemTime();//+QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
            }
            else
            {
                cpStr="SystemTime="+station.getSystemTime();//QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
            }

            netBox.writeDataToHost(index,host,500,HJ212::ResponseData(object,cpStr));//getDataPacket("QN="+object.QN+";ST=91;CN=1011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&"+cpStr+"&&"));

            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));

        }
        else if(1012==object.CN)
        {
            //QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));
            //取出
            if(object.CP.size()>5)
            {
                Device device("","");
                HJ212::recvCN1012(object.CP,device);
                //找出对应设备，根据协议取设置设备的时间
                station.setSystemTime(device.SystemTime);
            }

            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(1061==object.CN)
        {
            QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));
            //取出
            cpStr="RtdInterval="+station.getRtdInterval();
            netBox.writeDataToHost(index,host,500,HJ212::ResponseData(object,cpStr));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::ResponseData(object,cpStr));
            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(1062==object.CN)
        {
            //QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));
            //取出
            if(object.CP.size()>10)
            {
                station.setRtdInterval(HJ212::GetCpValueByKey(object.CP,"RtdInterval"));//textModel.setRtdInterval(HJ212::recvCN1062(object.CP));
            }
            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(1063==object.CN)
        {
            QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));
            //取出
            cpStr="MinInterval="+station.getMinInterval();
            netBox.writeDataToHost(index,host,500,HJ212::ResponseData(object,cpStr));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::ResponseData(object,cpStr));
            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(1064==object.CN)
        {
            //QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));
            //取出
            if(object.CP.size()>10)
            {
                station.setMinInterval(HJ212::GetCpValueByKey(object.CP,"MinInterval"));//textModel.setRtdInterval(HJ212::recvCN1062(object.CP));
            }
            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(1072==object.CN)
        {
            //QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));
            //取出
            if(object.CP.size()>10)
            {
                station.setPW(HJ212::GetCpValueByKey(object.CP,"NewPW"));//textModel.setRtdInterval(HJ212::recvCN1062(object.CP));
            }
            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(2011==object.CN)
        {
            //QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));

                station.setRealtimeReport("是");

            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(2012==object.CN)
        {
            //QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));

                station.setRealtimeReport("否");

            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(2021==object.CN)
        {
            //QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));

                station.setDeviceStateView("是");

            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }
        else if(2022==object.CN)
        {
            //QString cpStr;
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=1&&"));

                station.setDeviceStateView("否");

            netBox.writeDataToHost(index,host,500,HJ212::ReqResult(object));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9012;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&ExeRtn=1&&"));
        }

        else if(object.Flag==5)//需要应答的消息如果无法处理时返回"请求被拒绝"
        {
            netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object,2));//netBox.writeDataToNetWork(index,host.HostName,host.HostIp,host.HostPort,500,HJ212::getDataPacket("QN="+object.QN+";ST=91;CN=9011;PW="+object.PW+";MN="+object.MN+";Flag=4;CP=&&QnRtn=2&&"));
        }



        //测试站点数据更新
        station.setMN(object.MN);
        //textModel.setPW(object.PW);

    }
    else//返馈解包错误信息(请求命令返回)
    {
        netBox.writeDataToHost(index,host,500,HJ212::ReqReponse(object,error));
        //更新界面数据显示字串
        QString datastr="接收数据包错误:"+QString::number(error);
        hostlist.changeDataString(index,datastr);
    }



}



SerialPortHelper::~SerialPortHelper()
{


}
